﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace machine_registration.Services
{
 

    public static class AutoStartManager
    {
        private const string RunRegistryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";

        /// <summary>
        /// 发生错误时触发委托
        /// </summary>
        public static event EventHandler<Exception>? AutoStartChanged_Error;
        /// <summary>
        /// 查询是否已注册开机自启动
        /// </summary>
        /// <returns></returns>
        public static bool IsAutoStartEnabled()
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunRegistryKey, false))
            {
                return key?.GetValue(GetAppName()) != null;
            }
        }

        /// <summary>
        /// 开启开机自启动（返回操作是否成功）
        /// </summary>
        public static bool EnableAutoStart()
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunRegistryKey, true))
                {
                    if (key == null) return false; // 注册表项打开失败[1,4](@ref)

                    string appPath = GetAppPath();
                    key.SetValue(GetAppName(), appPath);

                    // 验证写入是否成功
                    return key.GetValue(GetAppName())?.ToString() == appPath;
                }
            }
            catch(Exception e)
            {
                AutoStartChanged_Error?.Invoke(null,e);
                return false; // 捕获所有异常（如权限不足）[1,4](@ref)
            }
        }

        /// <summary>
        /// 关闭开机自启动（返回操作是否成功）
        /// </summary>
        public static bool DisableAutoStart()
        {
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunRegistryKey, true))
                {
                    if (key == null) return false;

                    string appName = GetAppName();
                    key.DeleteValue(appName, false);

                    // 验证删除是否成功
                    return key.GetValue(appName) == null;
                }
            }
            catch (Exception e)
            {
                AutoStartChanged_Error?.Invoke(null, e);
                return false;
            }
        }
        // 获取当前应用程序的名称
        private static string GetAppName()
        {
            return System.Diagnostics.Process.GetCurrentProcess().ProcessName;
        }

        // 获取当前应用程序的路径
        private static string GetAppPath()
        {
            return System.Reflection.Assembly.GetEntryAssembly().Location;
        }
    }
}
